package com.cable.utils.tree;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 树形结构工具类，如：菜单、部门等
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0
 */
public class TreeUtils {

    /**
     * 根据pid，构建树节点
     */
    public static <T extends TreeNode> List<T> build(List<T> treeNodes, Long pid) {
        //pid不能为空
        Assert.isNull(pid,"pid不能为空");

        List<T> treeList = new ArrayList<>();
        for(T treeNode : treeNodes) {
            if (pid.equals(treeNode.getPid())) {
                treeList.add(findChildren(treeNodes, treeNode));
            }
        }

        return treeList;
    }

    /**
     * 查找子节点
     */
    private static <T extends TreeNode> T findChildren(List<T> treeNodes, T rootNode) {
        for(T treeNode : treeNodes) {
            if(rootNode.getId().equals(treeNode.getPid())) {
                rootNode.getChildren().add(findChildren(treeNodes, treeNode));
            }
        }
        return rootNode;
    }

    /**
     * 构建树节点
     */
    public static <T extends TreeNode> List<T> build(List<T> treeNodes) {
        List<T> result = new ArrayList<>();

        //list转map
        Map<Long, T> nodeMap = new LinkedHashMap<>(treeNodes.size());
        for(T treeNode : treeNodes){
            nodeMap.put(treeNode.getId(), treeNode);
        }

        for(T node : nodeMap.values()) {
            T parent = nodeMap.get(node.getPid());
            if(parent != null && !(node.getId().equals(parent.getId()))){
                parent.getChildren().add(node);
                continue;
            }

            result.add(node);
        }

        return result;
    }


    /**
     * 构建树节点,并排序
     */
    public static <T extends TreeNode> List<T> buildAndSortTree(List<T> treeNodes, Comparator<T> comparator) {
        List<T> result = new ArrayList<>();

        //list转map
        Map<Long, T> nodeMap = new LinkedHashMap<>(treeNodes.size());
        for(T treeNode : treeNodes){
            nodeMap.put(treeNode.getId(), treeNode);
        }

        for(T node : nodeMap.values()) {
            T parent = nodeMap.get(node.getPid());
            if(parent != null && !(node.getId().equals(parent.getId()))){
                parent.getChildren().add(node);
                continue;
            }
            result.add(node);
        }
        CollUtil.sort(result, comparator);
        sortChildrenRecursively(result, comparator);
        return result;
    }

    /**
     * 递归排序子节点
     *
     * @param nodes      当前层级的节点列表
     * @param comparator 比较器
     * @param <T>        树节点类型
     */
    private static <T extends TreeNode> void sortChildrenRecursively(List<T> nodes, Comparator<T> comparator) {
        for (T node : nodes) {
            // 对当前节点的子节点进行排序
            CollUtil.sort(node.getChildren(), comparator);
            // 递归排序子节点
            sortChildrenRecursively(node.getChildren(), comparator);
        }
    }
    public static <E> List<E> makeTree(List<E> list, Predicate<E> rootCheck, BiFunction<E, E, Boolean> parentCheck,
        BiConsumer<E, List<E>> setSubChildren) {
        return list.stream().filter(rootCheck).peek(x -> setSubChildren.accept(
            x,
            makeChildren(x, list, parentCheck, setSubChildren)
        )).collect(
            Collectors.toList());
    }

    private static <E> List<E> makeChildren(E parent, List<E> allData, BiFunction<E, E, Boolean> parentCheck,
        BiConsumer<E, List<E>> setSubChildren) {
        return allData.stream().filter(x -> parentCheck.apply(parent, x)).peek(x -> setSubChildren.accept(
            x,
            makeChildren(x,
                         allData,
                         parentCheck,
                         setSubChildren
            )
        )).collect(Collectors.toList());
    }

}